package com.atguigu.gulimall.cart.service.imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.to.SkuInfoVo;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import com.atguigu.gulimall.cart.vo.CartItemVo;
import com.atguigu.gulimall.cart.vo.CartVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImp implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor poolExecutor;

    private static final String CART_PREFIX = "gulimall:cart:";


    /**
     * 将商品添加到购物车
     *
     * @param skuId 商品id
     * @param num   商品数量
     * @return
     */
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        //1、获取要操作的购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        //1.1)、判断当前购物车中是否已存在当前商品
        String res = (String) cartOps.get(skuId.toString());
        if (!StringUtils.isEmpty(res)) {
            CartItemVo cartItemVo = new CartItemVo();
            //已存在，则直接修改当前商品的数量
            cartItemVo = JSON.parseObject(res, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItemVo));
            return cartItemVo;
        } else {
            CartItemVo cartItemVo = new CartItemVo();
            //不存在，则添加新商品
            //2、获取商品信息
            //2.1)、远程调用->异步查询具体的商品信息
            CompletableFuture<Void> getSkuInfo = CompletableFuture.runAsync(() -> {
                R skuInfo = productFeignService.getSkuInfo(skuId);
                if (skuInfo.getCode() == 0) {
                    SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    cartItemVo.setCheck(true);
                    cartItemVo.setCount(num);
                    cartItemVo.setImage(data.getSkuDefaultImg());
                    cartItemVo.setTitle(data.getSkuTitle());
                    cartItemVo.setSkuId(skuId);
                    cartItemVo.setPrice(data.getPrice());
                }
            }, poolExecutor);

            //2.2)、远程调用->异步查询当前商品的销售属性组合
            CompletableFuture<Void> getSkuSaleInfo = CompletableFuture.runAsync(() -> {
                List<String> list = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttr(list);
            }, poolExecutor);

            //等待两个异步查询都完成
            CompletableFuture.allOf(getSkuInfo, getSkuSaleInfo).get();

            //2.3）、将新商品保存到购物车中
            String jsonString = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), jsonString);

            return cartItemVo;
        }


    }

    /**
     * 根据skuId，从购物车中获取某一项商品信息
     *
     * @param skuId
     * @return
     */
    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(s, CartItemVo.class);
        return cartItemVo;
    }

    /**
     * 获取整个购物车信息
     *
     * @return
     */
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //1、已登录
            String userKey = CART_PREFIX + userInfoTo.getUserId();
            //判断临时购物车中是否存在数据【合并购物车】
            List<CartItemVo> tempCartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
            if (tempCartItems != null && tempCartItems.size() > 0) {
                //将临时购物车数据添加到用户购物车中
                for (CartItemVo item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                //清空临时购物车数据
                cleanCart(CART_PREFIX + userInfoTo.getUserKey());
            }
            //再获取合并后的用户购物车
            List<CartItemVo> cartItems = getCartItems(userKey);
            cartVo.setItems(cartItems);
        } else {
            //2、没登录,则获取临时购物车中的所有购物项信息
            String userKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItemVo> cartItems = getCartItems(userKey);
            cartVo.setItems(cartItems);
        }


        return cartVo;
    }

    /**
     * 清空指定购物车
     *
     * @param cartKey
     */
    @Override
    public void cleanCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    /**
     * 修改购物项的勾选状态
     *
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItemVo cartItemVo = getCartItem(skuId);
        cartItemVo.setCheck((check == 1 ? true : false));
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItemVo));
    }

    /**
     * 修改购物项数量
     *
     * @param skuId
     * @param num
     */
    @Override
    public void countItem(Long skuId, Integer num) {
        CartItemVo cartItemVo = getCartItem(skuId);
        cartItemVo.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItemVo));
    }

    /**
     * 删除某个购物项
     *
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 根据用户id，获取当前用户购物车中所有已选中的购物项(更新价格)
     *
     * @return
     */
    @Override
    public List<CartItemVo> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            //未登录
            return null;
        } else {
            //已登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItemVo> cartItems = getCartItems(cartKey);
            //只留下已选中的购物项
            List<CartItemVo> cartItemVos = cartItems.stream().filter((item) -> {
                return item.getCheck();
            }).collect(Collectors.toList());

            //TODO 更新商品的价格为最新价格
            //1、获取所有商品项skuId的集合
            List<Long> ids = cartItemVos.stream().map((item) -> {
                return item.getSkuId();
            }).collect(Collectors.toList());
            //2、远程调用->商品服务，获取每个sku对应的最新价格
            Map<Long, BigDecimal> newPrices = productFeignService.getPriceBySkuIds(ids);
            //3、更新每个商品的最新价格
            cartItemVos = cartItemVos.stream().map((item) -> {
                item.setPrice(newPrices.get(item.getSkuId()));
                return item;
            }).collect(Collectors.toList());

            return cartItemVos;
        }

    }


    /**
     * 返回要操作的购物车（用户购物车、临时购物车）
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //已登录，则操作用户购物车
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            //未登录，则操作临时购物车
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    /**
     * 根据cartKey获取当前购物车中的所有购物项
     *
     * @param cartKey
     * @return
     */
    private List<CartItemVo> getCartItems(String cartKey) {

        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItemVo> collect = values.stream().map((item) -> {
                String str = (String) item;
                CartItemVo cartItemVo = JSON.parseObject(str, CartItemVo.class);
                return cartItemVo;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }


}
